package com.dykj.fireFighting.web.controller;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.dykj.fireFighting.api.base.dev.entity.DeviceType;
import com.dykj.fireFighting.api.base.file.service.OfficeService;
import com.dykj.fireFighting.api.base.system.entity.SysDirectory;
import com.dykj.fireFighting.api.base.system.entity.SysDirectoryType;
import com.dykj.fireFighting.api.base.system.service.ISysDirectoryService;
import com.dykj.fireFighting.api.base.system.vo.SysDirectoryVo;
import com.dykj.fireFighting.api.monitoringCenter.entity.FireInformation;
import com.dykj.fireFighting.api.monitoringCenter.service.IFireInformationService;
import com.dykj.fireFighting.api.socialUnit.devicemanger.entity.Device;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.dto.CommonDto;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReader;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;



/**
 * 火灾记录接口
 *
 * @Author JacksonTu
 * @Date  2022-01-20 08:32:33
 */
@Slf4j
@Api(value = "火灾记录接口", tags = {"火灾记录接口"})
@RestController
@RequestMapping("fireInformation")
public class FireInformationController {

    @DubboReference
    private IFireInformationService fireInformationService;
    @DubboReference
    private ISysDirectoryService directoryService;
    @DubboReference(check = false)
    private OfficeService officeService;

    /**
     * 火灾记录列表
     *
     * @return
     */
    @AutoLog(value = "火灾记录-分页列表查询")
    @ApiOperation(value = "火灾记录分页列表", notes = "火灾记录分页列表")
    @GetMapping("/list")
    @RequiresPermissions("fireInformation/list")
    public CommonResult<PageVo<FireInformation>> treeGrid(CommonDto commonDto) {
        PageVo<FireInformation> page = fireInformationService.pageList(commonDto);
        return CommonResult.success(page);
    }

    @AutoLog(value = "火灾记录-获取地区")
    @ApiOperation(value = "火灾记录获取地区", notes = "火灾记录获取地区")
    @GetMapping("/getDic")
    //@RequiresPermissions("fireInformation/list")
    public CommonResult<List<SysDirectory>> getDic() {
        List<SysDirectory> list = directoryService.getByParentCode("130200000000");
        SysDirectory sysDirectory=directoryService.queryByCode("130200000000");
        list.add(sysDirectory);
        return CommonResult.success(list);
    }


    @AutoLog(value = "火灾记录-全市历年火灾数据格式")
    @ApiOperation(value = "全市历年火灾数据格式", notes = "全市历年火灾数据格式")
    @GetMapping("/getAllLnhz")
    //@RequiresPermissions("fireInformation/list")
    public CommonResult<List<Map<String,Object>>> getAllLnhz(String region) {
        Calendar cal = Calendar.getInstance();
        List<Integer> yearList=new ArrayList<>();
        yearList.add(cal.get(Calendar.YEAR));

        cal.setTime(new Date());
        cal.add(Calendar.YEAR, -1);
        yearList.add(cal.get(Calendar.YEAR));

        cal.setTime(new Date());
        cal.add(Calendar.YEAR, -2);
        yearList.add(cal.get(Calendar.YEAR));

        Map<String,Object> params=new HashMap<>();
        params.put("region",region);
        List<Map<String,Object>> getAllLnhz=fireInformationService.getAllLnhz(params);
        List<Map<String,Object>> result=new ArrayList<>();
        for (int i = 0; i < yearList.size(); i++) {
            Map<String,Object> map=new HashMap<>();
            int year=yearList.get(i);
            map.put("year",year);
            String[] strs= {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10","11","12"};
            map.put("month",strs);
            int[] countAll=new int[12];
            for (int j = 0; j < strs.length; j++) {
                String yearMonth=year+"-"+strs[j];
                int count=0;
                for (int k = 0; k < getAllLnhz.size(); k++) {
                    String key= (String) getAllLnhz.get(k).get("month");
                    if(yearMonth.equals(key)){
                        Object o=getAllLnhz.get(k).get("count");
                        String s=String.valueOf(o);
                        count= Integer.parseInt(s);
                    }
                }
                countAll[j]=count;
            }
            map.put("data",countAll);
            result.add(map);
        }
        return CommonResult.success(result);
    }



    @AutoLog(value = "火灾记录-各区历年火灾数据统计")
    @ApiOperation(value = "各区历年火灾数据统计", notes = "各区历年火灾数据统计")
    @GetMapping("/getAllGq")
    //@RequiresPermissions("fireInformation/list")
    public CommonResult<Map<String,Object>> getAllGq(String year,String region) {
        Map<String,Object> map=new HashMap<>();
        map.put("year",year);
        map.put("region",region);
        List<SysDirectory> list = directoryService.getByParentCode("130200000000");
        List<Map<String,Object>> getAllGq=fireInformationService.getAllGq(map);
        List<String> regionList=new ArrayList<>();
        List<Integer> dataList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String region1=list.get(i).getValue();
            int count=0;
            for (int j = 0; j < getAllGq.size(); j++) {
                String key= (String) getAllGq.get(j).get("region");
                if(region1.equals(key)){
                    Object o=getAllGq.get(j).get("count");
                    String s=String.valueOf(o);;
                    count= Integer.parseInt(s);
                }
            }
            regionList.add(region1);
            dataList.add(count);
        }
        map.put("regionList",regionList);
        map.put("dataList",dataList);
        return CommonResult.success(map);
    }

    @AutoLog(value = "火灾记录-起火原因统计")
    @ApiOperation(value = "起火原因统计", notes = "起火原因统计")
    @GetMapping("/getAllQhyy")
    //@RequiresPermissions("fireInformation/list")
    public CommonResult<List<Map<String,Object>>> getAllQhyy(String year,String region) {
        Map<String,Object> map=new HashMap<>();
        map.put("year",year);
        map.put("region",region);
        List<Map<String,Object>> getAllQhyy=fireInformationService.getAllQhyy(map);
        List<SysDirectory> list=directoryService.queryDataByType("fireReason");
        List<Map<String,Object>> dataList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> map1=new HashMap<>();
            String reason=list.get(i).getValue();
            int count=0;
            for (int j = 0; j < getAllQhyy.size(); j++) {
                String key= (String) getAllQhyy.get(j).get("reason");
                if(reason.equals(key)){
                    Object o=getAllQhyy.get(j).get("count");
                    String s=String.valueOf(o);;
                    count= Integer.parseInt(s);
                }
            }
            map1.put("name",reason);
            map1.put("value",count);
            dataList.add(map1);
        }
        return CommonResult.success(dataList);
    }
    @AutoLog(value = "火灾记录-各场所火灾统计")
    @ApiOperation(value = "各场所火灾统计", notes = "各场所火灾统计")
    @GetMapping("/getAllGcs")
    //@RequiresPermissions("fireInformation/list")
    public CommonResult<List<Map<String,Object>>> getAllGcs(String year,String region) {
        Map<String,Object> map=new HashMap<>();
        map.put("year",year);
        map.put("region",region);
        List<Map<String,Object>> getAllQhyy=fireInformationService.getAllGcs(map);
        List<SysDirectory> list=directoryService.queryDataByType("siteType");
        List<Map<String,Object>> dataList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> map1=new HashMap<>();
            String site=list.get(i).getValue();
            int count=0;
            for (int j = 0; j < getAllQhyy.size(); j++) {
                String key= (String) getAllQhyy.get(j).get("site");
                if(site.equals(key)){
                    Object o=getAllQhyy.get(j).get("count");
                    String s=String.valueOf(o);;
                    count= Integer.parseInt(s);
                }
            }
            map1.put("name",site);
            map1.put("value",count);
            dataList.add(map1);
        }
        return CommonResult.success(dataList);
    }

    @AutoLog(value = "火灾记录-各时段火灾数据统计")
    @ApiOperation(value = "各时段火灾数据统计", notes = "各时段火灾数据统计")
    @GetMapping("/getAllGsd")
    //@RequiresPermissions("fireInformation/list")
    public CommonResult<List<Map<String,Object>>> getAllGsd(String year,String region) {
        Map<String,Object> map=new HashMap<>();
        map.put("year",year);
        map.put("region",region);
        List<Map<String,Object>> getAllGsd=fireInformationService.getAllGsd(map);
        String[] strs= {"00", "02", "04", "06", "08", "10", "12", "14", "16", "18","20","22","24"};
        List<Map<String,Object>> dataList=new ArrayList<>();
        for (int i = 0; i < strs.length-1; i++) {
            Map<String,Object> map1=new HashMap<>();
            String time=strs[i];
            int count=0;
            for (int j = 0; j < getAllGsd.size(); j++) {
                String key= (String) getAllGsd.get(j).get("hTime");
                if(time.equals(key)){
                    Object o=getAllGsd.get(j).get("count");
                    String s=String.valueOf(o);;
                    count= Integer.parseInt(s);
                }
            }
            map1.put("name",time+"-"+strs[i+1]);
            map1.put("value",count);
            dataList.add(map1);
        }
        return CommonResult.success(dataList);
    }

    /**
     *下载设备导入模板
     */
    @GetMapping("/getImportModel")
    public CommonResult getImportModel() throws Exception {
        Map<String,Object> map=new HashMap<>();
        String id = officeService.saveEXceltoMongo(map, null, "fireInformation.xls", "火灾导入模板.xls");
        return CommonResult.success(id);
    }

    /**
     *批量导入火灾信息
     * @return
     */
    @PostMapping("/import")
    @RequiresPermissions("fireInformation/import")
    public CommonResult importDevice(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes){
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return CommonResult.failed("请上传文件");
        }
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx") && !fileName.endsWith(".xlsm")) {
            redirectAttributes.addFlashAttribute("message", "Please select a correct file to upload");
            return CommonResult.failed("文件格式错误");
        }
        LoginUserVo user = ShiroUtil.getUser();
        List<String> keyList=new ArrayList<>();
        keyList.add("area");keyList.add("fireReason");keyList.add("siteType");
        List<SysDirectoryVo> list=directoryService.queryDirectoryByType(keyList);
        String xmlConfig = "uploadXml/fireInformation.xml";
        try(InputStream xmlInputStream = getClass().getClassLoader().getResourceAsStream(xmlConfig)){
            XLSReader reader = ReaderBuilder.buildFromXML(xmlInputStream);
            try (InputStream xlsInputStream = new BufferedInputStream(file.getInputStream())){
                List<FireInformation> fireInformationList = new ArrayList<>();
                Map<String, Object> beans = new HashMap<>();
                beans.put("fireInformationList", fireInformationList);
                reader.read(xlsInputStream, beans);
                Map<String,Object> params=new HashMap<>();
                params.put("fireInformationList",fireInformationList);
                params.put("fireReason",list);
                params.put("user",user);
                int i = fireInformationService.importFire(params);
                if(i>0){
                    return CommonResult.success("导入完成，为您更新了" + i + "条数据");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("导入失败，请检查上传的文件信息");
        }
        return CommonResult.failed("导入失败，请检查上传的文件信息");
    }

    /**
     * 获取火灾记录信息
     */
    @AutoLog(value = "火灾记录-获取火灾记录信息")
    @ApiOperation(value = "获取火灾记录信息", notes = "获取火灾记录信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
    @RequiresPermissions("fireInformation/info")
    public CommonResult<FireInformation> info(@PathVariable("id") String id){
        FireInformation fireInformation = fireInformationService.getById(id);
        return CommonResult.success(fireInformation);
    }

    /**
     * 保存火灾记录信息
     */
    @AutoLog(value = "火灾记录-保存火灾记录信息")
    @ApiOperation(value = "保存火灾记录信息", notes = "保存火灾记录信息")
    @PostMapping("/save")
    @RequiresPermissions("fireInformation/save")
    public CommonResult save(@Valid @RequestBody FireInformation fireInformation) {
        try {
            fireInformation.setCreateTime(new Date());
                fireInformationService.save(fireInformation);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改火灾记录信息
     */
    @AutoLog(value = "火灾记录-修改火灾记录信息")
    @ApiOperation(value = "修改火灾记录信息", notes = "修改火灾记录信息")
    @PostMapping("/update")
    @RequiresPermissions("fireInformation/update")
    public CommonResult update(@Valid @RequestBody FireInformation fireInformation) {
        try {
                fireInformationService.updateById(fireInformation);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除火灾记录信息
     */
    @AutoLog(value = "火灾记录-删除火灾记录信息")
    @ApiOperation(value = "删除火灾记录信息", notes = "删除火灾记录信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
    @RequiresPermissions("fireInformation/delete")
    public CommonResult delete(@RequestBody String[]ids) {
        try {
                fireInformationService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }
}
